<template>
  <a-button @click="state.open=true"><import-outlined/>导入</a-button>
  <a-drawer title="导入产品报价" v-model:open="state.open" :width="600" >
    <a-flex justify="space-between" class="margin-bottom">
      <a-upload accept=".xlsx,.xls" :before-upload="beforeUpload" :show-upload-list="false">
        <a-button type="primary" :loading="state.importLoading">
          <UploadOutlined />上传
        </a-button>
      </a-upload>
      <a-space>
        <a-button @click="removeSelectedRows"><minus-circle-outlined/>移除</a-button>
        <a-button @click="removeAllRows"><close-outlined/>清空</a-button>
      </a-space>
    </a-flex>
    <a-table :columns="columns"
             :data-source="tableData"
             row-key="id"
             :row-selection="{selectedRowKeys:state.rowKey,onChange:onSelectedChange}"
             :pagination="false" size="small">

    </a-table>
    <template #footer>
      <a-flex justify="space-between">
        <a-button type="text" :href="templateUrl" target="_blank"><download-outlined/>下载模板</a-button>
        <a-space>
          <a-button>取消</a-button>
          <a-button type="primary" @click="onSubmit" :loading="state.loading">保存</a-button>
        </a-space>
      </a-flex>
    </template>
  </a-drawer>
</template>
<script lang="ts" setup>
import {
  ImportOutlined,
  UploadOutlined,
  DownloadOutlined,
    CloseOutlined,
  MinusCircleOutlined
} from "@ant-design/icons-vue";
import {reactive, ref} from "vue";
import {handleExcelImport, validateData} from "@/plugin/useExcel";
import {message} from "ant-design-vue";
import {getRandom} from "@/plugin/useFn";
import {createProduct} from "@/api/modules/product";
import {useUserStore} from "@/store/user";

interface TableItem {
  id?:number;
  name: string;
  category:string,
  cost_price:number|undefined,
  price:number|undefined,
  unit:string,
  user_id:number|undefined,
}
const templateUrl = '/product_template.xlsx'
const userStore = useUserStore()

const state = reactive({
  open:<boolean>false,
  importLoading:<boolean>false,
  rowKey:<RowKeysType[]>[],
  loading:false
})
const tableData = ref<TableItem[]>([])
const tableHeaders = ['名称', '分类', '进货价', '销售价', '单位'];

const columns: TableColumnsType = [
  { key: 'name', title: '产品名称', dataIndex: 'name' },
  { key: 'category', title: '分类', dataIndex: 'category' },
  { key: 'cost', title: '进货价',dataIndex: 'cost' },
  { key: 'price', title: '销售价',dataIndex: 'price' },
  { key: 'unit', title: '单位',dataIndex: 'unit'}
]
const beforeUpload = (file: File) => {
  state.importLoading = true;
  handleExcelImport(file, (importData) => {
    try {
      const [headers, ...rows] = importData;
      if (!validateData(headers, tableHeaders)) {
        message.error('文件格式不符合要求');
        return;
      } else if (rows.length === 0) {
        message.error('文件为空');
        return;
      }
      tableData.value = rows.map((row) => ({
        id: getRandom(8),
        name: String(row[0]),
        category: String(row[1]),
        cost_price: Number(row[2])|0,
        price: Number(row[3]) | 0,
        unit: String(row[4]),
        user_id: userStore.userInfo.id
      }));
      console.log(tableData.value);
      message.success(`成功导入${rows.length}条数据`);
    } catch (error) {
      message.error('数据解析失败' + error);
    } finally {
      state.importLoading = false;
    }
  });
  return false
}
const onSelectedChange = (selectedRowKeys: RowKeysType[]) => {
  state.rowKey = selectedRowKeys
  console.log(selectedRowKeys);
};
//删除选中的行
const removeSelectedRows = () => {
  if(!state.rowKey.length){
    return message.warn('请选择要删除的数据')
  }
  //删除选中的数据 rowKey
  //从tableData中删除选中id的数据
  state.rowKey.forEach((id) => {
    tableData.value = tableData.value.filter((row) => row.id !== id);
  });
}
//删除全部数据
const removeAllRows = () => {
  if(tableData.value.length === 0){
    return message.warn('请先上传数据')
  }
  tableData.value = []
}
const onSubmit = async () => {
  const data = {import:1,user_id:1, data:tableData.value}
  let res = await createProduct(data)
}
</script>